package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.ServiceItemQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ServiceItemServiceImpl implements IServiceItemService {

    @Autowired
    private ServiceItemMapper serviceItemMapper;

    @Autowired
    private IBpmnInfoService bpmnInfoService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private ICarPackageAuditService carPackageAuditService;

    @Override
    public TablePageInfo<ServiceItem> query(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<>(serviceItemMapper.selectForList(qo));
    }


    @Override
    public void save(ServiceItem serviceItem) {
        /**
         * 判断是否套餐,
         * 如果是套餐，需要把审核状态设置初始化
         * 如果不是套餐，需要把审核状态设置无需审核
         * 设置默认的销售状态和创建时间(防止前台恶意传参数进来)
         */
        //判断是否套餐,如果是套餐，需要把审核状态设置初始化
        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())) {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        } else {
            //如果不是套餐，需要把审核状态设置无需审核
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_NO_REQUIRED);
        }
        //设置默认的销售状态和创建时间(防止前台恶意传参数进来)
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        serviceItem.setCreateTime(new Date());
        serviceItemMapper.insert(serviceItem);
    }

    @Override
    public ServiceItem get(Long id) {
        return serviceItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(ServiceItem serviceItem) {
        //1.如果是上架状态，不允许修改的,抛出异常
        //2.如果是下架状态,非套餐(不需要处理)
        // 套餐，如果是审核中,不能进行编辑，抛出异常
        // 如果是下架状态，套餐，处于审核通过,如果此时修改，应该把状态修改成初始化
        // 其他情况，原来是什么状态，应该设置什么状态.
        // 非套餐--->无需审核
        // 套餐   ---->初始化，重新发起
        // 防止前台恶意对销售状态进行设置，代码中主动设置销售状态为下架状态
        ServiceItem oldObj = this.get(serviceItem.getId());
        if (ServiceItem.SALESTATUS_ON.equals(oldObj.getSaleStatus())) {
            //处于上架状态的商品不能修改
            throw new BusinessException("上架状态的商品不能修改,请在下架后再操作");
        } else if (ServiceItem.AUDITSTATUS_AUDITING.equals(oldObj.getAuditStatus())) {
            //处于审核中的商品,不可修改
            throw new BusinessException("商品正在审核中,不可修改");
        }
        //如果没上架,但审核通过了
        if (ServiceItem.AUDITSTATUS_APPROVED.equals(oldObj.getAuditStatus())) {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        }
        //如果不是套餐,需要设置审核状态为无需处理
        if (serviceItem.getAuditStatus().equals(ServiceItem.AUDITSTATUS_NO_REQUIRED)) {
            serviceItem.setSaleStatus(ServiceItem.AUDITSTATUS_NO_REQUIRED);
        }
        //如果是套餐,设置审核状态为初始化
        if (serviceItem.getCarPackage().equals(ServiceItem.CARPACKAGE_YES)) {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        }
        //为了安全性,修改时设置销售状态为修改前的状态
        serviceItem.setSaleStatus(oldObj.getSaleStatus());
        serviceItemMapper.updateByPrimaryKey(serviceItem);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            serviceItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<ServiceItem> list() {
        return serviceItemMapper.selectAll();
    }

    @Override
    public void saleOff(Long id) {
        serviceItemMapper.changeSaleStatus(id, ServiceItem.SALESTATUS_OFF);
    }

    @Override
    public void saleOn(Long id) {
        ServiceItem serviceItem = get(id);
        //如果不是套餐，可以直接上架
        //如果是套餐，只有审核成功才能上架
        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage()) &&
                !ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())) {
            throw new BusinessException("套餐服务项需要审核通过之后才能上架");
        }
        //如果不是套餐
        if (ServiceItem.SALESTATUS_OFF.equals(serviceItem.getCarPackage())) {
            serviceItemMapper.changeSaleStatus(id, ServiceItem.SALESTATUS_ON);
        }
        serviceItemMapper.changeSaleStatus(id, ServiceItem.SALESTATUS_ON);
    }

    @Override
    @Transactional
    public void startAudit(Long serverItemId, Long bpmnInfoId, Long director, Long finance, String info) {
        //根据id 查询服务项信息
        ServiceItem serviceItem = this.get(serverItemId);
        //合理性校验
        if (ServiceItem.CARPACKAGE_NO.equals(serviceItem.getCarPackage())
                || ServiceItem.AUDITSTATUS_AUDITING.equals(serviceItem.getAuditStatus())
                || ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())
                || ServiceItem.AUDITSTATUS_REPLY.equals(serviceItem.getAuditStatus())
                || ServiceItem.AUDITSTATUS_NO_REQUIRED.equals(serviceItem.getAuditStatus())
                || ServiceItem.SALESTATUS_ON.equals(serviceItem.getSaleStatus())
        ) {
            throw new BusinessException("非法操作,请联系管理员");
        }

        //审核信息记录
        CarPackageAudit audit = new CarPackageAudit();
        audit.setCreateTime(new Date()); //创建时间
        audit.setAuditorId(director);  //审核人
        audit.setCreator(ShiroUtils.getUser().getUserName()); //财务
        audit.setBpmnInfoId(bpmnInfoId); //流程定义ID
        audit.setInfo(info); //备注信息
        audit.setServiceItemId(serverItemId); //服务项ID
        audit.setServiceItemInfo(serviceItem.getInfo()); //服务项备注信息
        audit.setServiceItemPrice(serviceItem.getDiscountPrice());  //折扣价价格
        audit.setServiceItemName(serviceItem.getName()); //套餐名称

        //保存audit信息
        carPackageAuditService.save(audit);

        //获取bpmnInfo对象
        BpmnInfo bpmnInfo = bpmnInfoService.get(bpmnInfoId);
        Map<String, Object> param = new HashMap<>();
        if (director!=null) {
            param.put("director", director.toString());
        }
        if (finance != null) {
            param.put("finance", finance);
        }
        param.put("discountPrice", serviceItem.getDiscountPrice().longValue());

        //启动流程实例
        //参数 流程定义ID,业务ID(key)
        ProcessInstance instance = runtimeService.
                startProcessInstanceByKey(bpmnInfo.getActProcessKey(),
                audit.getId().toString(), param);

        //更新记录实例id
        audit.setInstanceId(instance.getId());
        carPackageAuditService.update(audit);

        //修改服务状态,修改为审核中
        serviceItemMapper.changeAuditStatus(serverItemId, ServiceItem.AUDITSTATUS_AUDITING);


    }

    @Override
    public void changeAuditStatus(Long serviceItemId, Integer status) {
        serviceItemMapper.changeAuditStatus(serviceItemId,status);
    }

    @Override
    public void updateAuditStatus(Long serviceItemId, Integer status) {
        serviceItemMapper.changeAuditStatus(serviceItemId,status);
    }
}
